<template>
  <div>
    <el-form class='input-form'
             label-position='right'
             label-width='120px'
             ref='editForm'
             :rules='propRules'
             :disabled='propReadonly'
             :model='form'
    >
      <el-row :gutter='20'>
        <el-col :span='6'>
          <el-form-item label='业务单号' prop='busKey'>
            <el-input v-model='form.busKey' disabled placeholder='自动设置' />
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label='采购科室'>
            <el-input v-model='form.deptName' disabled placeholder='自动获取' />
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label='采购日期' prop='busDate'>
            <el-date-picker v-model='form.busDate' type='date' :format='dates.defaultDatePattern'
                            :picker-options='dates.pickerOptions.date' />
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label='采购员' prop='busUser'>
            <el-input v-model='form.busUser' />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span='6'>
          <el-form-item label='供方名称' prop='supplierId'>
            <FortenDataviewDown
              ref='supplierName'
              propDownType='form'
              propFieldText='supplierName'
              :propForm='form'
              @select-change='selectSupplier'
              :propDisabledInput='propReadonly'
              :propUserParam="{viewKey: 'select_supplier'}"
            ></FortenDataviewDown>
          </el-form-item>
        </el-col>

        <el-col :span='6'>
          <el-form-item label='到货日期' prop='dateLates'>
            <el-date-picker ref='dateLates' v-model='form.dateLates' type='date'
                            :format='dates.defaultDatePattern'
                            :picker-options='dates.pickerOptions.futureDate' />
          </el-form-item>
        </el-col>

        <el-col :span='6'>
          <el-form-item label='订单类型' prop='poType'>
            <el-select v-model='form.poType' filterable disabled>
              <el-option v-for="dict in propDictionaries['poType']" :key='dict.value'
                         :label='dict.label'
                         :value='dict.value' />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label='一物一码' prop='flagOmoc'>
            <el-switch v-model='form.flagOmoc' active-color='#13ce66' disabled />
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter='20'>
        <el-col :span='6'>
          <el-form-item label='需求科室' prop='deptIdDemand'>
            <el-input v-model='form.deptNameDemand' disabled placeholder='自动获取' />
          </el-form-item>
        </el-col>

        <el-col :span='6'>
          <el-form-item label='收货仓库' prop='warehouseId'>
            <el-input v-model='form.warehouseName' disabled placeholder='自动获取' />
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label='订单金额(元)' prop='amount'>
            <el-input v-model.number='form.amount' disabled />
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label='备注' prop='remark'>
            <el-input v-model='form.remark' type='textarea' :rows='1' />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class='form-unit'>跟台采购单明细</div>
    <el-row class='package-btn'>
      <el-button type='primary' size='medium' @click='addPackage'
                 v-if="this.form.flowStatus === 'start' && this.getChildRows().length< 1 ">请选择跟台包
      </el-button>
    </el-row>
    <el-row>
      <div style='height:100%;overflow:auto;'>
        <packSelect
          ref='childDataView'
          propUrl='purchase/order_item/page'
          propFieldName='orderItemPackId'
          :propParentColumns='propParentColumns'
          :propReadonly='this.propReadonly'
          @childRowEdit='childRowEdit'
          @deletePackage='deletePackage'
          @deleteMatr='deleteMatr'
        />
        <el-dialog
          title='模板选择'
          :visible.sync='templetDialogVisible'
          :append-to-body='true'
          v-dialogDrag1
          v-dialog-resize
          width='80%'
          height='70vh'
          center
        >
          <templet-select ref='templetDataView' :propPackType='propPackType'
                          @confirm-check='confirmCheck'
                          :propDefaultInput='defaultInput' :propSupplierId='propSupplierId'
                      >
          </templet-select>
        </el-dialog>
      </div>
    </el-row>
  </div>
</template>

<script>

import SupplierSelect from '@/components/base/SupplierSelect'
import packSelect from '@/components/base/PackSelect.vue'
import templetSelect from '@/components/base/popover/PackTempletSelect.vue'

export default {
  data() {
    return {
      form: {},
      templetDialogVisible: false,
      propPackType: 'oper_bag',
      defaultInput: [],
      propParentColumns: [
        { label: '包名称', name: 'matrName' },
        { label: '数量', name: 'skuQty', width: 150 },
        { label: '金额', name: 'amount', width: 150 }
      ],
      viewData: {},
      currentRow: {},
      propSupplierId: ''
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        if (!this.form.supplierId) {
          this.utilMessage.warning('请选择供应商')
          this.$refs.supplierName.show()
          return
        }
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        // 设置switch默认值
        this.$set(this.form, 'flagOmoc', this.form.flagOmoc === undefined ? true : this.form.flagOmoc)
        if (!this.form.id) {
          //需求科室和采购科室为当前科室
          let CurrentUser = this.utils.getCurrentUser()
          this.$set(this.form, 'deptIdDemand', CurrentUser.deptId)
          this.$set(this.form, 'deptNameDemand', CurrentUser.deptName)
          this.$set(this.form, 'deptId', CurrentUser.deptId)
          this.$set(this.form, 'deptName', CurrentUser.deptName)
          this.$set(this.form, 'purchaseType', 'package')
          this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDatePattern))
          this.$set(this.form, 'poType', 'C')
          this.$set(this.form, 'supplierId', 0)
          this.setDefaultCenterWarehouse()

          this.$refs.supplierName.show()
        } else {
          let wrapper = this.getChildQueryWrapper()
          this.$refs.childDataView.setQueryWrapper(wrapper)
        }
      },
      afterSave: () => {

      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        let length = this.getChildRows().length
        if (length === 0) {
          this.utilMessage.error('请添加明细后提交')
          return false
        }
        return true
      },
      afterFlow: (flowButtonKey) => {
        return true
      },
      afterClick(button, data, viewForm) {
      },
      beforeClose: () => {
        return true
      }
    })
  },
  methods: {
    getChildQueryWrapper() {
      if (this.form.id) {
        return this.$newWrapper().eq('orderId', this.form.id).eq('matr_type', '1')
      } else {
        return this.$newWrapper().ne('1', 1)
      }
    },
    setDefaultCenterWarehouse() {
      let warehouseSet = this.utils.getCurrentWarehouse()

      if (!warehouseSet || !warehouseSet.id) {
        global.utilMessage.alertFail('未找到目标收货仓库，请到工作台检查是否已选择当前仓库!', '系统提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
            this.propParent.setViewFormVisible(false)
          }
        })
        return
      }
      this.$set(this.form, 'warehouseId', warehouseSet.id)
      this.$set(this.form, 'warehouseName', warehouseSet.warehouseName)
    },
    //选择供应商事件
    selectSupplier({ fieldText, row }) {
      this.$set(this.form, 'supplierId', row.id)
      this.$set(this.form, 'supplierName', row.name)
      if (!this.form.dateLates) this.$refs.dateLates.focus()
    },
    addPackage() {
      if (!this.form.id) {
        this.utilMessage.warning('请您先选择供应商')
        return
      }
      this.templetDialogVisible = true
      this.propSupplierId = this.form.supplierId
      this.$nextTick(() => {
        this.$refs.templetDataView.fetchData()
      })
    },
    fetchChildData() {
      this.$refs.childDataView.fetchData()
    },
    refreshData() {
      //刷新本页面表单
      this.propParent.ocRefreshCurrentRow()
      //刷新上级网格明细
      this.propParent.ocRefresh()
    },
    getChildRows() {
      if (!this.$refs.childDataView) {
        return []
      }
      return this.$refs.childDataView.getRows()
    },
    confirmCheck(rows) {
      //跟台包确认选择事件钩子
      if (!rows.length) {
        return
      }
      if (rows.length > 1) {
        this.utilMessage.warning('当前单据只支持单个跟台包采购，请重新选择')
        return
      }
      if (this.getChildRows().length > 0) {
        this.utilMessage.warning('当前订单已存在跟台包，请检查')
        return
      }
      let params = {
        orderId: this.form.id,
        packTemplets: rows
      }
      this.$ajax.post('/purchase/order_item/addByPack', params).then(response => {
        if (response.code === 0) {
          this.utilMessage.success(response.msg)
          this.refreshData()
        }
        this.templetDialogVisible = false
        this.fetchChildData()
      })
    },
    async childRowEdit({ row, column }) {
      this.$ajax.post('/purchase/order_item/updateQty', row).then(response => {
        this.refreshData()
        this.fetchChildData()
      })
    },
    deletePackage(row) {
      this.$confirm('此操作将永久删除该跟台包及包内耗材, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$ajax.delete('/purchase/order_item/deletePackage', { params: { id: row.id } }).then(response => {
            this.utilMessage.success('删除成功!')
            this.refreshData()
            this.fetchChildData()
          })
        })
        .catch(() => {
          this.utilMessage.info('已取消删除')
        })
    },
    deleteMatr(row) {
      this.$confirm('此操作将永久删除该跟台包及包内耗材, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$ajax.delete('/purchase/order_item/deleteMatr', { params: { id: row.id } }).then(response => {
            this.utilMessage.success('删除成功!')
            this.refreshData()
            this.fetchChildData()
          })
        })
        .catch(() => {
          this.utilMessage.info('已取消删除')
        })
    }
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propParentPage: Object
  },
  components: {
    SupplierSelect,
    packSelect,
    templetSelect
  },
  computed: {},
  watch: {}
}
</script>

<style lang='scss' scoped>
.container {
  width: 100%;
  height: 100%;
}

.package-btn {
  margin: 15px 0 15px 0;
}
</style>
